package cn.raven.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomFilter extends ZuulFilter {
    /**
    * @Title: filterType
    * @Description: 返回的什么拦截器   前置就返回  "pre"    后置返回"post"
    * @Author: king
    * @Version: 1.0
    * @Date:  2022/7/31 11:16
    * @Parameters: []
    * @Return java.lang.String
      */
    @Override
    public String filterType() {
        return "pre";
    }

    // 优先级 数字越小优先级越高
    @Override
    public int filterOrder() {
        return 0;
    }

    //是否执行下面的run方法，false拦截，true执行
    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        //如果是登录注册等资源就不进run
        if (uri.endsWith("register") || uri.contains("login") || uri.contains("static")){
            return false;
        }
        return true;
    }

    //登录信息校验
    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token) && !tokenIsTrue(token)){
            Map<String, Object> map = new HashMap<>();
            map.put("success" , false);
            map.put("message" , "未登录");
            response.setContentType("application/json;charset=utf-8");
            //把map转成json字符串，写到浏览器
            String resultJsonString = JSON.toJSONString(map);
            response.setStatus(HttpServletResponse.SC_PAYMENT_REQUIRED);
            try {
                response.getWriter().print(resultJsonString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }

    private boolean tokenIsTrue(String token) {
        return false;
    }
}
